import validator from 'validator';
import { Op } from 'sequelize';
import models from '../../models';
import { QueryWhereConf, AddPermissionError } from 'definitions/permission';
import { QueryAllConf } from 'definitions/common';
import { initRedis } from '../../bin/init';

const { AdminPermission, AdminPermissionClassify } = models;

export default function (router) {
  /**
   * 获取权限列表
   * @param {String} name 权限名称
   * @param {String} route 权限路径
   * @param {Boolean} all 是否查询全部
   * @param {Number} page 查询页数
   * @param {Number} limit 每页限制数
   */
  router.get('/api/admin/permission', async ctx => {
    const { name, route, classify, sorter, all } = ctx.request.query;
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);

    let whereConf: QueryWhereConf = {};
    if (name) {
      whereConf.name = {
        [Op.like]: `%${name}%`
      };
    }

    if (route) {
      whereConf.interface = {
        [Op.like]: `%${route}%`
      };
    }

    if (classify) {
      whereConf.classify_id = +classify;
    }

    // 排序规则
    let order = [['created_at', 'DESC']];
    if (sorter) {
      const sortName = sorter.split('_')[0].replace('createdAt', 'created_at').replace('updatedAt', 'updated_at');
      const sortFunc = sorter.split('_')[1].replace('ascend', 'ASC').replace('descend', 'DESC');
      order = [[sortName, sortFunc]];
    }

    // 是否获取全部数据
    const allConf: QueryAllConf = {};
    if (!all) {
      allConf.offset = (page - 1) * limit;
      allConf.limit = limit;
    }

    const classifies = await AdminPermission.findAndCountAll({
      ...allConf,
      where: whereConf,
      include: [{ model: models.AdminPermissionClassify, attributes: ['id', 'name'], as: 'classify' }],
      order: order
    });
    await ctx.json(true, '获取权限成功', { total: classifies.count, list: classifies.rows });
  });

  /**
   * 新增权限
   * @param {String} name 权限名称
   * @param {String} interface 接口地址
   * @param {String} description 权限描述
   */
  router.post('/api/admin/permission', async ctx => {
    let { name = '', description = '', classify, url = '' } = ctx.request.body;
    // 验证参数
    let error: AddPermissionError = {};
    if (!name || !validator.isLength(name, { min: 2, max: 10 })) error.name = '权限名称格式错误';
    if (await AdminPermission.isRepeat('name', name)) error.name = '权限名称重复';
    if (await AdminPermission.isRepeat('interface', url)) error.url = '接口地址重复';
    if (!await AdminPermissionClassify.findByPk(classify)) error.classify = '权限分类不存在';
    if (JSON.stringify(error) !== '{}') {
      await ctx.json(false, 'validate-error', error);
      return;
    }

    // 创建权限
    const newPermission = await AdminPermission.create({
      name,
      interface: url,
      classify_id: classify,
      description
    });

    if (newPermission && newPermission.id) {
      // 更新缓存中的权限数据
      initRedis();
      await ctx.json(true, '权限创建成功', newPermission);
    } else {
      await ctx.json(false, '权限创建失败');
    }
  });

  /**
   * 修改权限
   * @param {String} name 权限名称
   * @param {String} interface 接口地址
   * @param {String} description 权限描述
   */
  router.put('/api/admin/permission/:id', async ctx => {
    let { name = '', description = '', classify, url = '' } = ctx.request.body;
    const permissionId = ctx.params.id;
    // 验证参数
    let error: AddPermissionError = {};
    let params: AddPermissionError = {};
    if (classify) {
      if (!await AdminPermissionClassify.findByPk(classify)) error.classify = '权限分类不存在';
      params.classify_id = classify;
    }
    if (name) {
      if (!validator.isLength(name, { min: 2, max: 10 })) error.name = '权限名格式错误';
      if (await AdminPermission.isRepeat('name', name, 'self')) error.name = '权限名重复';
      params.name = name;
    }
    if (url) {
      params.interface = url;
    }
    if (description || description === '') {
      params.description = description;
    }
    if (JSON.stringify(error) !== '{}') {
      await ctx.json(false, 'validate-error', error);
      return;
    }
    // 更新权限
    const updateResult = await AdminPermission.update(params, {
      where: { id: permissionId }
    });
    if (updateResult[0] === 1) {
      // 更新缓存中的权限数据
      initRedis();
      await ctx.json(true, '更新权限成功');
    } else {
      await ctx.json(false, '更新权限失败');
    }
  });

  /**
   * 删除权限
   */
  router.delete('/api/admin/permission/:id', async ctx => {
    const { id } = ctx.params;
    // 删除权限
    const deleteResult = await AdminPermission.destroy({ where: { id } });
    // TODO 删除分类下的权限
    // 更新缓存中的权限数据
    initRedis();
    if (deleteResult === 1) {
      await ctx.json(true, '删除权限成功');
    } else {
      await ctx.json(false, '删除权限失败');
    }
  });
}
